package ferp.core.state;

import ferp.core.calc.Calculator;
import ferp.core.game.Game;
import ferp.core.game.Input;
import ferp.core.game.Settings;
import ferp.core.mode.Mode;
import ferp.core.player.Profile;

/**
 * User: user
 * Date: 5/28/12 10:40 PM
 */
class End extends State
{
  @Override
  public int process(Game.Listener listener, Profile profile, Game g, Settings settings, Input input) throws Game.Error
  {
    // update the number of sets played
    ++g.sets;
    g.statistics.sets.deals = g.sets;

    // update profile version
    ++profile.version;

    if (Calculator.get(settings.gameFlavor).over(g, settings) || g.tutorial())
      over(listener, profile, g, settings);
    else
      dealing(listener, profile, g, settings);

    return Result.SCHEDULE;
  }

  private void over(Game.Listener listener, Profile profile, Game g, Settings settings)
  {
    if (g.tutorial())
      profile.tutorialStatus = Profile.TutorialStatus.COMPLETED;
    else
    {
      // update game's statistics
      g.statistics.numOfGames = 1;
      g.statistics.totalPool = settings.poolSize;

      // update total statistics
      profile.getStatistics().update(g.statistics);
    }

    // clear game objects
    profile.clearGame();

    // save the game state
    save(profile);

    // fire game over event
    listener.onGameOver(g);
  }

  private void dealing(Game.Listener listener, Profile profile, Game g, Settings settings)
  {
    // set next dealer - if playing passing type classical the next dealer always is the same player inside
    // consequent passing set. Here g.consequentPassingSets == 0 means no passing was played, so dealer can be switched
    // normally regardless the passing type.
    if (settings.passingType == Settings.PassingType.SLIDING || g.consequentPassingSets == 0)
      g.player.dealer = Game.next(g.player.dealer);

    // go back to dealing mode
    g.set(Mode.dealing);

    // save the game state
    save(profile);

    // fire set over event
    listener.onSetOver(g);
  }
}
